package cn.com.jdyun.job;

import cn.com.jdyun.dto.GainsDTO;
import cn.com.jdyun.exception.BdexGatewayException;
import cn.com.jdyun.mapper.ext.ExtSysConfigMapper;
import cn.com.jdyun.pojo.SysConfig;
import cn.com.jdyun.pojo.UserWallet;
import cn.com.jdyun.service.GainsService;
import cn.com.jdyun.service.LockCoinService;
import cn.com.jdyun.service.RefereeService;
import cn.com.jdyun.service.TransferService;
import cn.com.jdyun.service.UserWalletService;
import cn.com.jdyun.util.Constant;
import cn.com.jdyun.util.RedisUtil;
import cn.com.jdyun.util.WebConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author admin
 * @date Created in 上午 11:56 2018/8/27 0027
 */
@Component
public class CheckIsSuperPartner {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(CheckIsSuperPartner.class);

    @Autowired
    UserWalletService userWalletService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    RefereeService refereeService;
    @Autowired
    TransferService transferService;
    @Autowired
    GainsService gainsService;
    @Autowired
    LockCoinService lockCoinService;
    @Autowired
    ExtSysConfigMapper sysConfigMapper;

//    @Scheduled(cron = "0 0 1 * * ?") //每天凌晨1点执行
    //@Scheduled(initialDelay=30, fixedDelay=60*60*1000) //启动后执行，间隔一小时再执行
    public void isSuperPartnerOrNot() throws BdexGatewayException {
        SysConfig communityRewardPercentConfig = sysConfigMapper.selectByCode(Constant.communityRewardPercent);
        SysConfig communityPartnerRewardPercentConfig = sysConfigMapper.selectByCode(Constant.communityPartnerRewardPercent);
        SysConfig texCommunityRewardPercentConfig = sysConfigMapper.selectByCode(Constant.texCommunityRewardPercent);
        SysConfig texCommunityPartnerRewardPercentConfig = sysConfigMapper.selectByCode(Constant.texCommunityPartnerRewardPercent);
    	//查询所有超级节点
        Set<String> superNodeIds = refereeService.queryAllSuperNodeId();
    	//查询所有Tex超级节点
        Set<String> superTexNodeIds = refereeService.queryAllTexSuperNodeId();
        //查询所有合伙人
        if(superNodeIds!=null && superNodeIds.size()>0){
            Set<String> partnerIds = refereeService.queryAllPartnerId(superNodeIds);
            if(partnerIds != null && partnerIds.size() > 0) {
                partnerIds.addAll(superNodeIds);
            }else {
                partnerIds = superNodeIds;
            }
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            String date = WebConstants.dateFormat.format(calendar.getTime());
            BigDecimal curVest = null;
            String[] arr = null;
            boolean exists = false;
            for (String userId : partnerIds) {
                //查询该节点下的所有挖矿节点
                List<GainsDTO> gainsList = gainsService.queryPartnerRelation(userId, Constant.COINTYPE_SSSP, date);
                BigDecimal curUserIncome = new BigDecimal("0");
                for (GainsDTO gains : gainsList) {
                    //判断该节点之前的节点是否存在合伙人（不是当前结算的合伙人，但是在当前结算的合伙人之后）
                    exists = false;
                    arr = gains.getContext().split(userId);
                    //获取当前正在结算的合伙人节点之后的部分
                    arr = arr[1].split(gains.getUserId());
                    //获取当前用户节点之前的部分
                    arr = arr[0].split("/");
                    if (arr != null && arr.length > 0) {
                        //查看是否存在其它合伙人
                        for (String str : arr) {
                            if (StringUtils.isBlank(str)) {
                                continue;
                            }
                            if (partnerIds.contains(str)) {
                                exists = true;
                                break;
                            }
                        }
                    }
                    //如果中间不存在合伙人节点，则表明是当前合伙人的直系节点
                    if (!exists) {
                        Map<String, String> details = new HashMap<>();
                        if (partnerIds.contains(gains.getUserId())) {
                            //合伙人
                            curVest = new BigDecimal(gains.getVested()).multiply(new BigDecimal(communityPartnerRewardPercentConfig.getInitValue())).setScale(6, BigDecimal.ROUND_HALF_DOWN);
                            curUserIncome = curUserIncome.add(curVest);
                            details.put(gains.getUserId(), "-->" + gains.getVested() + " * " + communityPartnerRewardPercentConfig.getInitValue() + " = " + curVest);
                        } else {
                            curVest = new BigDecimal(gains.getVested()).multiply(new BigDecimal(communityRewardPercentConfig.getInitValue())).setScale(6, BigDecimal.ROUND_HALF_DOWN);
                            curUserIncome = curUserIncome.add(curVest);
                            details.put(gains.getUserId(), "-->" + gains.getVested() + " * " +communityRewardPercentConfig.getInitValue()+ " = " + curVest);
                        }
                        log.info(">>> " + userId + " : get:[" + curUserIncome + "] ---> details:" + details.toString());
                    }
                }
                if (curUserIncome.doubleValue() <= 0) {
                    continue;
                }
                try {
                    //判断当前收益是否大于用户锁仓(奖励总额不能超过用户当前锁仓总额)
                    UserWallet wallet = userWalletService.queryByUserIdAndConiType(userId, Constant.COINTYPE_SSSP);
                    if (wallet.getLockedCoin().compareTo(curUserIncome) < 0) {
                        curUserIncome = wallet.getLockedCoin();
                        log.info(">>> " + userId + " : get:[" + curUserIncome + "] ---> details: wallet.getLockedCoin().compareTo(curUserIncome) < 0 (wallet.getLockedCoin():" + wallet.getLockedCoin() + ")");
                    }
                    userWalletService.updatePartnerIncome(userId, curUserIncome, Constant.COINTYPE_SSSP, date);
                } catch (Exception e) {
                    log.error("计算合伙人收益保存失败：userId:" + userId + ", curUserIncome" + curUserIncome + ", coinType:" + Constant.COINTYPE_SSSP + ", date:" + date + ", errorMessage:" + e.getMessage());
                }
            }
        }


        //查询所有Tex合伙人
        if(superTexNodeIds!=null && superTexNodeIds.size()>0){
            Set<String> texPartnerIds = refereeService.queryAllTexPartnerId(superTexNodeIds);
            if(texPartnerIds != null && texPartnerIds.size() > 0) {
                texPartnerIds.addAll(superTexNodeIds);
            }else {
                texPartnerIds = superTexNodeIds;
            }
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            String date = WebConstants.dateFormat.format(calendar.getTime());
            BigDecimal curVest = null;
            String[] arr = null;
            boolean exists = false;
            for (String userId : texPartnerIds) {
                //查询该节点下的所有挖矿节点
                List<GainsDTO> gainsList = gainsService.queryPartnerRelation(userId, Constant.COINTYPE_TEX, date);
                BigDecimal curUserIncome = new BigDecimal("0");
                for (GainsDTO gains : gainsList) {
                    //判断该节点之前的节点是否存在合伙人（不是当前结算的合伙人，但是在当前结算的合伙人之后）
                    exists = false;
                    arr = gains.getContext().split(userId);
                    //获取当前正在结算的合伙人节点之后的部分
                    arr = arr[1].split(gains.getUserId());
                    //获取当前用户节点之前的部分
                    arr = arr[0].split("/");
                    if (arr != null && arr.length > 0) {
                        //查看是否存在其它合伙人
                        for (String str : arr) {
                            if (StringUtils.isBlank(str)){
                                continue;
                            }
                            if (texPartnerIds.contains(str)) {
                                exists = true;
                                break;
                            }
                        }
                    }
                    //如果中间不存在合伙人节点，则表明是当前合伙人的直系节点
                    if (!exists) {
                        Map<String, String> details = new HashMap<>();
                        if (texPartnerIds.contains(gains.getUserId())) {
                            //合伙人
                            curVest = new BigDecimal(gains.getVested()).multiply(new BigDecimal(texCommunityPartnerRewardPercentConfig.getInitValue())).setScale(6, BigDecimal.ROUND_HALF_DOWN);
                            curUserIncome = curUserIncome.add(curVest);
                            details.put(gains.getUserId(), "-->" + gains.getVested() + " * " + texCommunityPartnerRewardPercentConfig.getInitValue() + " = " + curVest);
                        } else {
                            curVest = new BigDecimal(gains.getVested()).multiply(new BigDecimal(texCommunityRewardPercentConfig.getInitValue())).setScale(6, BigDecimal.ROUND_HALF_DOWN);
                            curUserIncome = curUserIncome.add(curVest);
                            details.put(gains.getUserId(), "-->" + gains.getVested() + " * " + texCommunityRewardPercentConfig.getInitValue() + " = " + curVest);
                        }
                        log.info(">>> " + userId + " : get:[" + curUserIncome + "] ---> details:" + details.toString());
                    }
                }
                if (curUserIncome.doubleValue() <= 0) {
                    continue;
                }
                try {
                    //判断当前收益是否大于用户锁仓(奖励总额不能超过用户当前锁仓总额)
                    UserWallet wallet = userWalletService.queryByUserIdAndConiType(userId, Constant.COINTYPE_TEX);
                    if (wallet.getLockedCoin().compareTo(curUserIncome) < 0) {
                        curUserIncome = wallet.getLockedCoin();
                        log.info(">>> " + userId + " : get:[" + curUserIncome + "] ---> details: wallet.getLockedCoin().compareTo(curUserIncome) < 0 (wallet.getLockedCoin():" + wallet.getLockedCoin() + ")");
                    }
                    userWalletService.updatePartnerIncome(userId, curUserIncome, Constant.COINTYPE_TEX, date);
                } catch (Exception e) {
                    log.error("计算合伙人收益保存失败：userId:" + userId + ", curUserIncome" + curUserIncome + ", coinType:" + Constant.COINTYPE_TEX+ ", date:" + date + ", errorMessage:" + e.getMessage());
                }
            }
        }
    }

    /*public  void isSuperPartnerOrNot() throws BdexGatewayException {
        List<Map<String,Object>> resultList = new ArrayList<>();
        BigDecimal partnerProfit1 = new BigDecimal("0").setScale(6, BigDecimal.ROUND_HALF_UP);
        BigDecimal commonProfit1 = new BigDecimal("0").setScale(6, BigDecimal.ROUND_HALF_UP);
        BigDecimal totalProfit1 = new BigDecimal("0").setScale(6, BigDecimal.ROUND_HALF_UP);
        //查询锁仓额度大于1000的
        List<UserWallet> userWalletList = userWalletService.findSuperNodes(Constant.COINTYPE_SSSP, new BigDecimal(Constant.tinyMiningLowestLockCoinNum));
        for (UserWallet userWallet : userWalletList) {
            if (!userWallet.getUserId().equals(Constant.mainAccountId)) {
                String userId = userWallet.getUserId();
                Boolean isPartnerOrNot = refereeService.checkPartner(userId);
                Map<String, Object> resultMap;
                int partner = 0;
                //判断是否是合伙人
                if (isPartnerOrNot) {
                    //查询比特宝信息
                    UserWallet referee1Wallet = transferService.inqueryLockedCoinAmount(userId, Constant.COINTYPE_SSSP);
                    resultMap = profitCalc(referee1Wallet, totalProfit1, partnerProfit1, commonProfit1, partner);
                    resultList.add(resultMap);
                }
            }
        }
        //TODO 记录 resultList
    }

    private Map<String, Object> profitCalc(UserWallet userWallet, BigDecimal totalProfitNum, BigDecimal partnerProfitNum, BigDecimal commonProfitNum, int partner) throws BdexGatewayException {
        Map<String, Object> resultMap = new HashMap<>();
        //查询用户下二级锁仓的所有用户信息
        List<UserWallet> userWalletRefereeList = refereeService.queryAllUserWallet(userWallet.getUserId());
        Iterator iterator = userWalletRefereeList.iterator();
        while (iterator.hasNext()) {
            UserWallet wallet = (UserWallet) iterator.next();
            //判断是否是合伙人
            Boolean isPartner = refereeService.checkPartner(wallet.getUserId());
            Date date = new DateTime().minusDays(1).toDate();
            String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);
            Gains gains = gainsService.queryCurBalance(dateStr, wallet.getUserId());
            //用户昨日挖矿收入
            String vested = null;
            if(gains!=null){
                vested = gains.getVested();
                if (isPartner) {
                    //TODO 消息推送
                    //合伙人
                    //TODO 矿池中的数量的变化
                    BigDecimal perUserProfitNum = new BigDecimal(vested).multiply(new BigDecimal(Constant.communityPartnerRewardPercent)).setScale(6, BigDecimal.ROUND_HALF_UP);
                    totalProfitNum = totalProfitNum.add(perUserProfitNum);
                    partnerProfitNum = partnerProfitNum.add(perUserProfitNum);
                    partner = partner + 1;
                } else {
                    //普通用户
                    //TODO 矿池中的数量的变化
                    BigDecimal perUserProfitNum = new BigDecimal(vested).multiply(new BigDecimal(Constant.communityRewardPercent)).setScale(6, BigDecimal.ROUND_HALF_UP);
                    totalProfitNum = totalProfitNum.add(perUserProfitNum);
                    commonProfitNum = commonProfitNum.add(perUserProfitNum);
                }
                //排除是合伙人的下级还是合伙人就计算重复了，后其下有合伙人的情况
                Map<String, Object> resultMap1 = isPartner(wallet, totalProfitNum, userWalletRefereeList, partnerProfitNum, partner);
                totalProfitNum = (BigDecimal) resultMap1.get("totalProfit");
                partnerProfitNum = (BigDecimal) resultMap1.get("partnerProfit");
                partner = (int) resultMap1.get("belowPartnerNum");
            }
        }
        resultMap.put("totalProfit", totalProfitNum);
        resultMap.put("commonProfit", commonProfitNum);
        resultMap.put("partnerProfit", partnerProfitNum);
        resultMap.put("belowPartnerNum", partner);
        return resultMap;

    }

    private Map<String, Object> isPartner(UserWallet userWallet, BigDecimal totalProfitNum, List<UserWallet> walletRefereeList, BigDecimal partnerProfitNum, int partner) throws BdexGatewayException {
        List<User> userList = refereeService.userReferees(userWallet.getUserId());
        if (userList != null || userList.size() != 0) {
            //查询用户下二级锁仓的所有用户信息
            List<UserWallet> userWalletRefereeList = refereeService.queryAllUserWallet(userWallet.getUserId());
            for (UserWallet userWallet1 : walletRefereeList) {
                Iterator iterator = userWalletRefereeList.iterator();
                while (iterator.hasNext()) {
                    UserWallet wallet = (UserWallet) iterator.next();
                    if (userWallet1.getUserId().equalsIgnoreCase(wallet.getUserId())) {
                        iterator.remove();
                    }
                }
            }
            Iterator iterator = userWalletRefereeList.iterator();
            while (iterator.hasNext()) {
                UserWallet wallet = (UserWallet) iterator.next();
                //判断是否是合伙人
                Boolean isPartner = refereeService.checkPartner(wallet.getUserId());
                if (isPartner) {
                    //TODO 消息推送
                    Date date = new DateTime().minusDays(1).toDate();
                    String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);
                    Gains gains = gainsService.queryCurBalance(dateStr, wallet.getUserId());
                    //用户昨日挖矿收入
                    String vested = gains.getVested();
                    //TODO 矿池中的数量的变化
                    BigDecimal partnerProfit = new BigDecimal(vested).multiply(new BigDecimal(Constant.communityPartnerRewardPercent)).setScale(6, BigDecimal.ROUND_HALF_UP);
                    totalProfitNum = totalProfitNum.add(partnerProfit);
                    partnerProfitNum = partnerProfitNum.add(partnerProfit);
                    partner++;
                } else {
                    isPartner(userWallet, totalProfitNum, userWalletRefereeList, partnerProfitNum, partner);
                }
            }
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("totalProfit", totalProfitNum);
        resultMap.put("partnerProfit", partnerProfitNum);
        resultMap.put("belowPartnerNum", partner);
        return resultMap;

    }*/


//    public Map<String,Object> profitCalc(UserWallet userWallet, BigDecimal totalProfitNum,BigDecimal partnerProfitNum,BigDecimal commonProfitNum,int partner) throws BdexGatewayException {
//        Map<String,Object> resultMap  = new HashMap<>();
//        //查询用户下二级锁仓的所有用户信息
//        List<UserWallet> userWalletRefereeList = refereeService.queryAllUserWallet(userWallet.getUserId());
//        Iterator iterator = userWalletRefereeList.iterator();
//        while (iterator.hasNext()) {
//            UserWallet wallet = (UserWallet) iterator.next();
//            //判断是否是合伙人
//            Boolean isPartner = refereeService.checkPartner(wallet.getUserId());
//            Date date = new DateTime().minusDays(1).toDate();
//            String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);
//            Gains gains = gainsService.queryCurBalance(dateStr, wallet.getUserId());
//            //用户昨日挖矿收入
//            String vested = gains.getVested();
//            if (isPartner) {
//                //合伙人
//                BigDecimal perUserProfitNum = new BigDecimal(vested).multiply(new BigDecimal(Constant.communityPartnerRewardPercent));
//                totalProfitNum = totalProfitNum.add(perUserProfitNum);
//                partnerProfitNum = partnerProfitNum.add(perUserProfitNum);
//                partner = partner+1;
//            } else {
//                //普通用户
//                BigDecimal perUserProfitNum = new BigDecimal(vested).multiply(new BigDecimal(Constant.communityRewardPercent));
//                totalProfitNum = totalProfitNum.add(perUserProfitNum);
//                commonProfitNum = commonProfitNum.add(perUserProfitNum);
//            }
//            //排除是合伙人的下级还是合伙人就计算重复了，后其下有合伙人的情况
//            Map<String,Object> resultMap1 = isPartner(wallet, totalProfitNum, userWalletRefereeList,partnerProfitNum, partner);
//            totalProfitNum = (BigDecimal) resultMap1.get("totalProfit");
//            partnerProfitNum = (BigDecimal) resultMap1.get("partnerProfit");
//            partner = (int)resultMap1.get("belowPartnerNum");
//        }
//        resultMap.put("totalProfit",totalProfitNum);
//        resultMap.put("commonProfit",commonProfitNum);
//        resultMap.put("partnerProfit",partnerProfitNum);
//        resultMap.put("belowPartnerNum",partner);
//        return resultMap;
//
//    }
//
//    public Map<String,Object> isPartner(UserWallet userWallet, BigDecimal totalProfitNum, List<UserWallet> walletRefereeList,BigDecimal partnerProfitNum,int partner) throws BdexGatewayException {
//        List<User> userList = refereeService.userReferees(userWallet.getUserId());
//        if (userList != null || userList.size() != 0) {
//            //查询用户下二级锁仓的所有用户信息
//            List<UserWallet> userWalletRefereeList = refereeService.queryAllUserWallet(userWallet.getUserId());
//            for (UserWallet userWallet1 : walletRefereeList) {
//                Iterator iterator = userWalletRefereeList.iterator();
//                while (iterator.hasNext()) {
//                    UserWallet wallet = (UserWallet) iterator.next();
//                    if(userWallet1.getUserId().equalsIgnoreCase(wallet.getUserId())){
//                        iterator.remove();
//                    }
//                }
//            }
//            Iterator iterator = userWalletRefereeList.iterator();
//            while (iterator.hasNext()) {
//                UserWallet wallet = (UserWallet) iterator.next();
//                //判断是否是合伙人
//                Boolean isPartner = refereeService.checkPartner(wallet.getUserId());
//                if (isPartner) {
//                    Date date = new DateTime().minusDays(1).toDate();
//                    String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);
//                    Gains gains = gainsService.queryCurBalance(dateStr, wallet.getUserId());
//                    //用户昨日挖矿收入
//                    String vested = gains.getVested();
//                    BigDecimal partnerProfit = new BigDecimal(vested).multiply(new BigDecimal(Constant.communityPartnerRewardPercent));
//                    totalProfitNum = totalProfitNum.add(partnerProfit);
//                    partnerProfitNum = partnerProfitNum.add(partnerProfit);
//                    partner++;
//                } else {
//                    isPartner(userWallet, totalProfitNum,userWalletRefereeList, partnerProfitNum, partner);
//                }
//            }
//        }
//
//        Map<String,Object> resultMap = new HashMap<>();
//        resultMap.put("totalProfit",totalProfitNum);
//        resultMap.put("partnerProfit",partnerProfitNum);
//        resultMap.put("belowPartnerNum",partner);
//        return resultMap;
//
//    }


}
